<script>
  let tree = $state([]);
  for (let i = 0; i < 10; i++) {
    tree.push({
      id: i,
      name: `Node ${i}`,
      open: false,
      children: Array.from({ length: 10 }, (_, j) => ({
        id: `${i}-${j}`,
        name: `Node ${i}-${j}`,
        open: false,
        children: Array.from({ length: 10 }, (_, k) => ({
          id: `${i}-${j}-${k}`,
          name: `Node ${i}-${j}-${k}`,
          children: [],
        })),
      })),
    });
  }
  //   let treeMap = {};
  //   function convertToMap(tree) {
  //     tree.forEach((item) => {
  //       treeMap[item.id] = item;
  //       convertToMap(item.children);
  //     });
  //   }
  //   convertToMap(tree);
  //   let toTree = $state(treeMap);
  function toggle(id) {
    let ee = `${id}`.split("-");
    let dots = [];
    ee.forEach((a) => {
      dots.push([...dots, a].join("-"));
    });
    console.log(dots);

    let target = null;
    let scane = tree;
    dots.forEach((a) => {
      target = scane.find((b) => b.id == a);
      scane = target.children;
    });
    target.open = !target.open;
  }
</script>

{#snippet treeNodes(list)}
  {#each list as item}
    <div class="tree-node">
      <div
        role="button"
        tabindex="0"
        class="tree-node-name"
        onclick={(e) => toggle(item.id) && e.stopPropagation()}
        onkeydown={(e) => {}}
      >
        {item.name}
      </div>
      <div class={["tree-children", item.open && "open"]}>
        {#if item.children.length > 0}
          {@render treeNodes(item.children)}
        {/if}
      </div>
    </div>
  {/each}
{/snippet}
<div class="tree">
  {@render treeNodes(tree)}
</div>

<style lang="scss">
  .tree {
    .tree-node {
      font-size: 13px;
      .tree-children {
        margin-left: 20px;
        display: none;
        &.open {
          display: block;
        }
      }
    }
  }
</style>
